package com.hanoi.wiki.manager.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hanoi.wiki.dao.UserDAO;
import com.hanoi.wiki.dao.UserStatisticDAO;
import com.hanoi.wiki.exception.DataAccessException;
import com.hanoi.wiki.manager.UserStatisticManager;
import com.hanoi.wiki.model.User;
import com.hanoi.wiki.model.UserStatistic;
import com.hanoi.wiki.model.json.UserStatisticJson;

@Component
@Transactional
public class UserStatisticManagerImpl extends BaseManagerImpl implements UserStatisticManager{
	
	@Autowired
	private UserStatisticDAO userStatisticDAO;
	
	@Autowired
	private UserDAO userDAO;

	public int save(UserStatisticJson json) {
		try {
			UserStatistic userStatistic = new UserStatistic(json);
			
			User user = userDAO.get(json.getUser());
			if(user != null) {
				userStatistic.setUser(user);
			}
			
			return userStatisticDAO.saveUserStatistic(userStatistic);
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return 0;
	}

	public void update(UserStatisticJson json) {
		try {
			UserStatistic userStatistic = new UserStatistic(json);
			
			User user = userDAO.get(json.getUser());
			if(user != null) {
				userStatistic.setUser(user);
			}
			userStatistic.setId(json.getId());
			
			userStatisticDAO.update(userStatistic);
		} catch (DataAccessException e) {
			log.error("", e);
		}
	}

	public UserStatisticJson get(Integer id) {
		try {
			return new UserStatisticJson(userStatisticDAO.get(id));
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return null;
	}

	public List<UserStatisticJson> getList() {
		List<UserStatisticJson> userStatiList = new ArrayList<UserStatisticJson>();
		List<UserStatistic> statisticsList = userStatisticDAO.getList();
		try {
			for(UserStatistic statistic : statisticsList) {
				userStatiList.add(new UserStatisticJson(statistic));
			}
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return userStatiList;
	}

	public void remove(Integer id) {
		try {
			if(userStatisticDAO.get(id) != null) {
				userStatisticDAO.remove(id);
			}
		} catch (DataAccessException e) {
			log.error("", e);
		}
	}
}
